//
// Created by zx208 on 2024/10/27.
//

#include "LinkedQueue.h"

Status InitQueue(LinkedQueue *Q) {
    // front rear 指向同一节点
    Q->front = Q->rear = (QueueNode *)malloc(sizeof(QueueNode));
    if(!Q->front) exit(OVERFLOW);

    Q->front->next = NULL; //使该节点next域为NULL
    return OK;
}

Status Entry_LQ(LinkedQueue *Q, ElemType e) {
    QueueNode *p = (QueueNode *)malloc(sizeof(QueueNode));
    if (!p) exit(OVERFLOW);
    p->data = e;
    p->next = NULL;
    Q->rear->next = p; // 将新元素接到队尾
    Q->rear = p; // 修改队尾指针
    return OK;
}

Status Out_LQ(LinkedQueue *Q, ElemType *e) {
    if (Q->front == Q->rear) return ERROR;
    QueueNode *pfree = Q->front->next;
    *e = pfree->data;
    Q->front->next = pfree->next;
    // 特殊情况 当元素出队后发现队列中没有元素时，将尾指针修改成头指针
    if (Q->rear == pfree)
        Q->rear = Q->front;
    free(pfree);
    return OK;
}

Status IsEmpty(LinkedQueue *Q){
    return Q->front == Q->rear;
}

void Destroy_LQ(LinkedQueue *Q){
    // 结果是头结点也会被销毁
    while(Q->front){
        Q->rear = Q->front->next;
        free(Q->front);
        Q->front = Q->rear;
    }
}

int main(void){
    LinkedQueue Q;
    InitQueue(&Q);
    Entry_LQ(&Q, 1);
    Entry_LQ(&Q, 2);
    Entry_LQ(&Q, 3);
    Entry_LQ(&Q, 4);
    ElemType e;
    while (!(IsEmpty(&Q))){
        Out_LQ(&Q, &e);
        printf("%d ", e);
    }
    return 0;
}